package org.misty.redis.autoconfigure.usage.autoconfig;

import org.misty.redis.bloomfilter.BloomFilter;
import org.misty.redis.cache.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author Misty on 2020-06-13
 */
@SpringBootApplication
@RestController
public class AutoConfigApplication {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private RedisCache<String> redisCache;

    @PostConstruct
    private void init() {
        for (int i = 0; i < 100; i++) {
            redisCache.getFilter().put(String.valueOf(i));
        }
    }

    @GetMapping("/{id:\\d+}")
    public String index(@PathVariable String id) {
        String cacheKey = "cache:test:" + id;
        return redisCache.scope(id)
            .hit(ctx -> redisTemplate.opsForValue().get(cacheKey))
            .miss(ctx -> {
                System.out.println("miss");
                try {
                    TimeUnit.MILLISECONDS.sleep(100 + ThreadLocalRandom.current().nextInt(100));
                } catch (InterruptedException ignore) {
                }
                String value = new Date().toString();
                redisTemplate.opsForValue().set(cacheKey, value);
                return value;
            }).get();
    }

    public static void main(String[] args) {
        SpringApplication.run(AutoConfigApplication.class, args);
    }
}
